﻿using System;
using System.Collections.Generic;
using System.Threading;
using BLL;
using Model;

public partial class InstrumentManage_AutoViewENAState : System.Web.UI.Page
{
    Microsoft.VisualBasic.Devices.Computer com = new Microsoft.VisualBasic.Devices.Computer();
    private static int pcount, fcount;
    private static List<ENAInfo> eNAs;
    private static List<ENAInfo> eNAInfos;
    ENA eNA;

    public InstrumentManage_AutoViewENAState()
    {
        eNA = new ENA();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        eNAInfos = (List<ENAInfo>)eNA.GetENAs();
        Timer1_Tick(sender, e);
    }

    protected void Ping(object o)
    {        
        int i = Convert.ToInt32(o);
        bool result = com.Network.Ping(eNAInfos[i].ENAIP);
        if (result == true)
        {
            Interlocked.Increment(ref pcount);
        }
        else
        {
            Interlocked.Increment(ref fcount);
            lock (eNAs)
            {
                eNAs.Add(eNAInfos[i]);
            }
        }
    }

    protected void PingENA()
    {
        pcount = 0;
        fcount = 0;
        eNAs = new List<ENAInfo>();
        int i;
        int n = eNAInfos.Count;
        Thread[] thr = new Thread[n];
        for (i = 0; i < n; i++)
        {
            thr[i] = new Thread(new ParameterizedThreadStart(Ping));
            thr[i].Start(i);
        }
        for (int j = 0; j < n; j++)
        {
            thr[j].Join();
        }
    }

    protected void Timer1_Tick(object sender, EventArgs e)
    {
        PingENA();
        Label2.Text = DateTime.Now.ToLongTimeString();
        this.Label3.Text = pcount.ToString();
        this.Label4.Text = fcount.ToString();
        if (fcount > 0)
            this.Image1.ImageUrl = "~/Images/InstrumentManage/RedBall.png";
        else
            this.Image1.ImageUrl = "~/Images/InstrumentManage/GreenBall.png";
        this.GridView1.DataSource = (IList<ENAInfo>)eNAs;
        this.GridView1.DataBind();
    }
}
